<script setup lang="ts">
import type { FormInstance, UploadUserFile } from "element-plus"
import { saveAsScenarioApi, searchScenarioBasic } from "@/common/apis/scn"
import { ElMessage, ElMessageBox } from "element-plus"
import { cloneDeep, isEqual } from "lodash-es"
import { computed, ref, watch } from "vue"

interface Props {
  id: string | undefined
  visible: boolean
}

const props = defineProps<Props>()
const emit = defineEmits(["closeDialog"])
const DEFAULT_FORM_DATA = {
  id: undefined,
  scnName: "",
  description: ""
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref(cloneDeep(DEFAULT_FORM_DATA))
const formRules = {
  scnName: [{ required: true, trigger: "blur", message: "请输入" }],
}
const loading = ref<boolean>(false)
const detailLoading = ref<boolean>(false)
const isEdit = ref<boolean>(false)
const defaultFormData = ref(cloneDeep(DEFAULT_FORM_DATA))

const textMap = computed(() => {
  return "另存为"
})
function getScnInfo() {
  detailLoading.value = true
  props.id
  && searchScenarioBasic(props.id)
    .then(({ data }) => {
      if (data) {
        formData.value = {
          scnName: data.scnName,
          description: data.description
         }
      } else {
        ElMessage("数据不存在")
      }
    })
    .finally(() => {
      detailLoading.value = false
    })
}
function showDialog() {
  formRef.value?.resetFields()
  isEdit.value = false
  detailLoading.value = false
  getScnInfo()
}
function closeDialog() {
  formRef.value?.resetFields()
  emit("closeDialog", undefined)
}
function handleConfirm() {
  formRef.value?.validate(async (valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const params = {
      id: props.id,
      scnName: formData.value.scnName,
      description: formData.value.description
    }
    saveAsScenarioApi(params)
      .then(() => {
        ElMessage.success("操作成功")
        emit("closeDialog", "refresh")
      })
      .finally(() => {
        loading.value = false
      })
  })
}
function handleCloseTip(done: () => void) {
  // 校验值是否相同
  if (isEqual(defaultFormData.value, formData.value)) {
    closeDialog()
    done()
    return
  }
  ElMessageBox.confirm("当前编辑未保存，是否确定关闭？").then(() => {
    done()
  })
}

watch(
  () => [props.id, props.visible],
  () => {
    dialogVisible.value = props.visible
    if (props.visible) {
      showDialog()
    }
  }
)
</script>

<template>
  <el-drawer
    v-model="dialogVisible"
    direction="rtl"
    size="600px"
    @close-auto-focus="closeDialog"
    @close="closeDialog"
    :before-close="handleCloseTip"
    :show-close="false"
    :append-to-body="true"
  >
    <template #header>
      <div class="drawer-header">
        <h4>{{ textMap }}</h4>
      </div>
    </template>
    <template #default>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        width="600"
        label-width="90px"
        label-position="right"
        :close-on-click-modal="false"
        v-loading="detailLoading"
      >
        <el-form-item label="想定名称" prop="scnName">
          <el-input v-model="formData.scnName" autocomplete="off" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            :rows="3"
            type="textarea"
            placeholder="请输入"
            maxlength="600"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button plain v-throttle="() => closeDialog()">
          取 消
        </el-button>
        <el-button :loading="loading" type="primary" v-throttle="() => handleConfirm()">
          确 定
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style lang="scss" scoped>
.upload-demo {
  width: 100% !important;
}
:deep(.el-upload.el-upload--text) {
  width: 100% !important;
}
</style>
